//
//  GoodsDetailsViewController.m
//  PrintPort
//
//  Created by 华谕 on 2017/11/22.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "GoodsDetailsViewController.h"
#import "GoodsModel.h"
#import "SizeListModel.h"
#import "SizeDetailModel.h"
#import "ImagelistModel.h"
#import "SDCycleScrollView.h"
#import <QuartzCore/QuartzCore.h>
#import "JSBadgeView.h"
#import "FeedBackViewController.h"
#import "WebHelpViewController.h"
#import "BuyNowViewController.h"

static NSString *cellPath = @"GoodsDetailsCell";
static NSString *ggCellPath = @"ggCell";

@interface GoodsDetailsViewController ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate,UIWebViewDelegate,UIScrollViewDelegate,UITextFieldDelegate>
{
    CGFloat heightX;
    UIScrollView *titScrollview;
    UIView *bottonLine;
    UILabel *tongjiLab;
}
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)UITableView *ggTableview;
@property (nonatomic, strong)GoodsModel *model;
@property (nonatomic, strong)SDCycleScrollView *cycleScrollView;
@property (nonatomic, strong)UIWebView *webView;
@property (nonatomic, strong)UIView *closeGgView;
@property (nonatomic, strong)NSArray *typeGgAry;
@property (nonatomic, strong)NSMutableDictionary *closeGoodsDic;
@property (nonatomic, assign)NSInteger indexrow;
@property (nonatomic, strong)NSMutableDictionary *priceDic;
@property (nonatomic, strong)NSMutableDictionary *integDic;
@property (nonatomic, assign)BOOL isShopCar;
@property (nonatomic, assign)NSInteger allNumber;
@property (nonatomic, assign)CGFloat allPrice;
@property (nonatomic, assign)CGFloat allInteger;


@end

@implementation GoodsDetailsViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jianpanhuishou:) name:UIKeyboardWillHideNotification object:nil];
    self.navigationController.navigationBar.hidden = YES;

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _closeGoodsDic = [NSMutableDictionary dictionaryWithCapacity:0];
    _priceDic = [NSMutableDictionary dictionaryWithCapacity:0];
    _integDic = [NSMutableDictionary dictionaryWithCapacity:0];
    _indexrow = 0;
    _allNumber = 0;
    _allPrice = 0;
    _allInteger = 0;
    [self creatUI];
    [self requestProductSelect];
}

- (void)creatUI
{
    self.view.backgroundColor = BacksColor;
    self.navigationController.navigationBar.hidden = YES;
    heightX = 0;
    if (SCREEN_HEIGHT == 812)
    {
        heightX = 34;
    }
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, -STATUSBAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT+STATUSBAR_HEIGHT-45*displaywidth-heightX) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.tag = 11;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableview.backgroundColor = BacksColor;
    [self.view addSubview:_tableview];
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 300*displaywidth)];
    self.cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 300*displaywidth) delegate:self placeholderImage:nil];
    _cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    _cycleScrollView.delegate = self;
    //是否自动轮播
    _cycleScrollView.autoScroll = YES;//是否自动轮播 bannerImageViewContentMode
    //图片样式
    _cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
    _cycleScrollView.clipsToBounds = YES;
    _cycleScrollView.currentPageDotColor = ThemeColor;
    _cycleScrollView.pageDotColor = [UIColor whiteColor];
    _cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleClassic;
    [headerView addSubview:_cycleScrollView];
    
    self.tableview.tableHeaderView = headerView;
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, STATUSBAR_HEIGHT, SCREEN_WIDTH, 60*displaywidth)];
    topView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:topView];
    
    UIButton *backBtn = [ZCControl createButtonWithFrame:CGRectMake(10*displaywidth, 10*displaywidth, 40*displaywidth, 40*displaywidth) ImageName:@"fanhui222" Target:self Action:@selector(backAction) Title:nil Font:12.0];
    backBtn.backgroundColor = [UIColor clearColor];
    [topView addSubview:backBtn];
    
//    UIButton *shareBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-110*displaywidth, 10*displaywidth, 40*displaywidth, 40*displaywidth) ImageName:@"fenxiang" Target:self Action:@selector(shareAction) Title:nil Font:12.0];
//    shareBtn.backgroundColor = [UIColor clearColor];
//    [topView addSubview:shareBtn];
    
    UIButton *feedbackBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-50*displaywidth, 10*displaywidth, 40*displaywidth, 40*displaywidth) ImageName:@"yijianfankui" Target:self Action:@selector(feedbackAction) Title:nil Font:12.0];
    feedbackBtn.backgroundColor = [UIColor clearColor];
    [topView addSubview:feedbackBtn];
    
    UIView *bottonView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-45*displaywidth-heightX, SCREEN_WIDTH, 45*displaywidth)];
    bottonView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottonView];
    UIButton *addShopBtn = [ZCControl createButtonWithFrame:CGRectMake(0 , 0, SCREEN_WIDTH/2, 45*displaywidth) ImageName:nil Target:self Action:@selector(addShopAction) Title:@"加入购物车" Font:15.0];
    [addShopBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
    addShopBtn.backgroundColor = [UIColor whiteColor];
    [bottonView addSubview:addShopBtn];
    UIButton *BuyBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH/2 , 0, SCREEN_WIDTH/2, 45*displaywidth) ImageName:nil Target:self Action:@selector(buyAction) Title:@"立即购买" Font:15.0];
    [BuyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    BuyBtn.backgroundColor = ThemeColor;
    [bottonView addSubview:BuyBtn];
}

- (void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
    self.navigationController.navigationBar.hidden = NO;
}

//分享
//- (void)shareAction
//{
//
//}

//反馈
- (void)feedbackAction
{
    FeedBackViewController *vc = [[FeedBackViewController alloc] init];
    vc.pladerStr = @"请输入遇到的问题或建议...";
    vc.titleStr = @"意见反馈";
    [self.navigationController pushViewController:vc animated:YES];
}

//加入购物车
- (void)addShopAction
{
    _isShopCar = YES;
    _closeGgView.hidden = NO;
}
//立即购买
- (void)buyAction
{
    _isShopCar = NO;
    _closeGgView.hidden = NO;

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == 11)
    {
        return 4;

    }
    else
    {
        return _typeGgAry.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 11)
    {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if (!cell)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (_model)
        {
            UIView *lineV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
            lineV.backgroundColor = LinesColor;
            [cell.contentView addSubview:lineV];
            if (indexPath.row == 0)
            {
                UILabel *titleLabel = [ZCControl createLabelWithFrame:CGRectMake(20*displaywidth, 0, SCREEN_WIDTH- 40*displaywidth, 30*displaywidth) Font:14.0 Text:_model.productName Color:RGB(77, 77, 77)];
                [cell.contentView addSubview:titleLabel];
//                NSString *priceStr = [NSString stringWithFormat:@" %@元",_model.price];
//                if ([LTools storageForKey:SERVER_isPass])
//                {
//                    priceStr = [NSString stringWithFormat:@" %@积分",_model.price];
//                }
//                UILabel *priceLabel = [ZCControl createLabelWithFrame:CGRectMake(20*displaywidth, 45*displaywidth, 140*displaywidth, 30*displaywidth) Font:14.0 Text:priceStr Color:RGB(255, 111, 28)];
//                [cell.contentView addSubview:priceLabel];
//                UIButton *priceBtn = [ZCControl createButtonWithFrame:CGRectMake(20*displaywidth, 45*displaywidth, 140*displaywidth, 30*displaywidth) ImageName:@"jifen" Target:nil Action:nil Title:string(@" ", _model.price) Font:14.0];
//                priceBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
//                priceBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//                priceBtn.backgroundColor = [UIColor clearColor];
//                [priceBtn setTitleColor:priceColor forState:UIControlStateNormal];
//                [cell.contentView addSubview:priceBtn];
                UILabel *moneyLab = [ZCControl createLabelWithFrame:CGRectMake(20*displaywidth, 45*displaywidth, 140*displaywidth, 30*displaywidth) Font:12.0 Text:[NSString stringWithFormat:@"%@ +",_model.priceDescribe] Color:RGB(241, 90, 36)];
                CGRect abounds = [moneyLab.text boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-200*displaywidth, 20*displaywidth) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:NormalFontWithSize(12.0+fontScale)} context:nil];
                CGFloat width1 = abounds.size.width+20;
                moneyLab.frame = CGRectMake(20*displaywidth, 45*displaywidth, width1, 30*displaywidth);
                [cell.contentView addSubview:moneyLab];
                
                UILabel *integralLab = [ZCControl createLabelWithFrame:CGRectMake(width1+25*displaywidth, 50*displaywidth, 120*displaywidth, 20*displaywidth) Font:11.0 Text:[NSString stringWithFormat:@"%@积分",_model.integral] Color:[UIColor whiteColor]];
                integralLab.textAlignment = NSTextAlignmentCenter;
                integralLab.layer.cornerRadius = 2;
                integralLab.layer.masksToBounds = YES;
                integralLab.backgroundColor = RGB(24, 159, 186);
                [cell.contentView addSubview:integralLab];
                CGRect bounds1 = [integralLab.text boundingRectWithSize:CGSizeMake(120*displaywidth, 20*displaywidth) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:NormalFontWithSize(11.0+fontScale)} context:nil];
                CGFloat width2 = bounds1.size.width+10;
                if (bounds1.size.width > 120*displaywidth)
                {
                    width2 = 120*displaywidth;
                }
                integralLab.frame = CGRectMake(width1+25*displaywidth, 50*displaywidth, width2, 20*displaywidth);
                
                UILabel *historyLabel = [ZCControl createLabelWithFrame:CGRectMake(SCREEN_WIDTH/2+20*displaywidth, 50*displaywidth, 100*displaywidth, 20*displaywidth) Font:11.0 Text:[NSString stringWithFormat:@"%@购买",_model.productSales] Color:RGB(179, 179, 179)];
                [cell.contentView addSubview:historyLabel];
                
                UILabel *numLabel = [ZCControl createLabelWithFrame:CGRectMake(SCREEN_WIDTH-115*displaywidth, 50*displaywidth, 100*displaywidth, 20*displaywidth) Font:11.0 Text:[NSString stringWithFormat:@"%@库存",_model.productStock] Color:RGB(179, 179, 179)];
                numLabel.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:numLabel];
            }
            else if (indexPath.row == 1 || indexPath.row == 2)
            {
                NSString *name = @"规格型号";
                if (indexPath.row == 2)
                {
                    name = @"售后服务";
                }
                UILabel *nameLab = [ZCControl createLabelWithFrame:CGRectMake(20*displaywidth, 0, 140*displaywidth, 30*displaywidth) Font:14.0 Text:name Color:RGB(77, 77, 77)];
                [cell.contentView addSubview:nameLab];
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }
            else
            {
                UIView *grayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10*displaywidth)];
                grayView.backgroundColor = BacksColor;
                [cell.contentView addSubview:grayView];
                UILabel *Label = [ZCControl createLabelWithFrame:CGRectMake(20*displaywidth, 10*displaywidth, 140*displaywidth, 30*displaywidth) Font:14.0 Text:@"商品详情" Color:RGB(77, 77, 77)];
                [cell.contentView addSubview:Label];
                if (![_model.proDescribe isEqualToString:@""])
                {
                    if (!self.webView)
                    {
                        [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
                        _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 40*displaywidth, SCREEN_WIDTH, 200*displaywidth)];
                        _webView.delegate = self;
                        _webView.scrollView.scrollEnabled = NO;
                        //预先加载url
                        [self.webView loadHTMLString:_model.proDescribe baseURL:nil];
                    }
                    [cell.contentView addSubview:_webView];
                    
                }
                
            }
        }
        return cell;
    }
    else
    {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if (!cell)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ggCellPath];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (_typeGgAry.count > 0)
        {
            SizeDetailModel *model = _typeGgAry[indexPath.row];
            UILabel *nameLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 5*displaywidth, 180*displaywidth, 25*displaywidth) Font:14.0 Text:model.productSizeDetailName Color:RGB(77, 77, 77)];
            [cell.contentView addSubview:nameLab];
            UILabel *priceLab = [ZCControl createLabelWithFrame:CGRectMake(17.5*displaywidth, 30*displaywidth, 180*displaywidth, 15*displaywidth) Font:11.0 Text:[NSString stringWithFormat:@"￥%@元 + %@积分",model.price,model.integral] Color:RGB(179, 179, 179)];
            [cell.contentView addSubview:priceLab];
            UILabel *kucunLab = [ZCControl createLabelWithFrame:CGRectMake(SCREEN_WIDTH-200*displaywidth, 5*displaywidth, 70*displaywidth, 40*displaywidth) Font:11.0 Text:[NSString stringWithFormat:@"库存：%@",model.productStock] Color:RGB(179, 179, 179)];
            kucunLab.textAlignment = NSTextAlignmentRight;
            [cell.contentView addSubview:kucunLab];
            UIView *numView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-125*displaywidth, 10*displaywidth, 110*displaywidth, 30*displaywidth)];
            numView.backgroundColor = [UIColor whiteColor];
            numView.layer.cornerRadius = 2;
            numView.layer.masksToBounds = YES;
            numView.layer.borderColor = RGB(204, 204, 204).CGColor;
            numView.layer.borderWidth = 1;
            [cell.contentView addSubview:numView];
            UIView *line01 = [[UIView alloc] initWithFrame:CGRectMake(29*displaywidth, 0, 1*displaywidth, 30*displaywidth)];
            line01.backgroundColor = RGB(204, 204, 204);
            [numView addSubview:line01];
            UIView *line02 = [[UIView alloc] initWithFrame:CGRectMake(80*displaywidth, 0, 1*displaywidth, 30*displaywidth)];
            line02.backgroundColor = RGB(204, 204, 204);
            [numView addSubview:line02];
            UIButton *deleteBtn = [ZCControl createButtonWithFrame:CGRectMake(0, 0, 30*displaywidth, 30*displaywidth) ImageName:nil Target:self Action:@selector(deleteBtnAction:) Title:@"-" Font:16.0];
            deleteBtn.backgroundColor = [UIColor clearColor];
            [deleteBtn setTitleColor:RGB(179, 179, 179) forState:UIControlStateNormal];
            deleteBtn.tag = indexPath.row + 200;
            [numView addSubview:deleteBtn];
            UIButton *addBtn = [ZCControl createButtonWithFrame:CGRectMake(80*displaywidth, 0, 30*displaywidth, 30*displaywidth) ImageName:nil Target:self Action:@selector(addBtnAction:) Title:@"+" Font:16.0];
            addBtn.backgroundColor = [UIColor clearColor];
            [addBtn setTitleColor:RGB(179, 179, 179) forState:UIControlStateNormal];
            addBtn.tag = indexPath.row + 2200;
            [numView addSubview:addBtn];
            UITextField *textfield = [ZCControl createTextFieldWithFrame:CGRectMake(30*displaywidth, 0, 50*displaywidth, 30*displaywidth) placeholder:@"0" passWord:NO leftImageView:nil rightImageView:nil Font:13.0];
            [textfield setValue:RGB(77, 77, 77) forKeyPath:@"_placeholderLabel.textColor"];
            textfield.textColor = RGB(77, 77, 77);
            textfield.textAlignment = NSTextAlignmentCenter;
            textfield.delegate = self;
            textfield.tag = indexPath.row + 3000;
            textfield.keyboardType = UIKeyboardTypeNumberPad;
            [numView addSubview:textfield];
            if ([_closeGoodsDic.allKeys containsObject:model.productSizeId])
            {
                NSDictionary *dic = [_closeGoodsDic objectForKey:model.productSizeId];
                if ([dic.allKeys containsObject:model.ID])
                {
                    NSString *numStr = [dic objectForKey:model.ID];
                    textfield.text = numStr;
                }
                else
                {
                    textfield.text = @"0";
                }
            }
            else
            {
                textfield.text = @"0";

            }
        }
        UIView *lineview33 = [[UIView alloc] initWithFrame:CGRectMake(0, 49, SCREEN_WIDTH, 1*displaywidth)];
        lineview33.backgroundColor = LinesColor;
        [cell.contentView addSubview:lineview33];
        return cell;
    }
    
   
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    //获取到webview的高度
    NSString *js= @"var script = document.createElement('script');"
    "script.type = 'text/javascript';"
    "script.text = \"function ResizeImages() { "
    "var myimg,oldwidth;"
    "var maxwidth = %f;"
    "for(i=0;i <document.images.length;i++){"
    "myimg = document.images[i];"
    "if(myimg.width > maxwidth){"
    "oldwidth = myimg.width;"
    "myimg.width = %f;"
    "}"
    "}"
    "}\";"
    "document.getElementsByTagName('head')[0].appendChild(script);";
    js=[NSString stringWithFormat:js,[UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.width-15];
    [webView stringByEvaluatingJavaScriptFromString:js];
    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
    CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
    self.webView.frame = CGRectMake(self.webView.frame.origin.x,self.webView.frame.origin.y, SCREEN_WIDTH, height+40*displaywidth);
    [self.tableview reloadData];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 1)
    {
        _isShopCar = YES;
        _closeGgView.hidden = NO;
    }
    else if (indexPath.row == 2)
    {
        WebHelpViewController *vc = [[WebHelpViewController alloc] init];
        vc.typeID = 4;
        vc.titleStr = @"售后服务";
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 11)
    {
        if (indexPath.row == 0)
        {
            return 80*displaywidth;
        }
        else if (indexPath.row == 3)
        {
            return _webView.frame.size.height+40*displaywidth;
        }
        else
        {
            return 30*displaywidth;
        }
    }
    else
    {
        return 50*displaywidth;
    }
   
}

//减少数量
- (void)deleteBtnAction:(UIButton *)btn
{
    NSInteger index = btn.tag-200;
    SizeDetailModel *model = _typeGgAry[index];
    if ([_closeGoodsDic.allKeys containsObject:model.productSizeId])
    {
        NSDictionary *dic = [_closeGoodsDic objectForKey:model.productSizeId];
        NSMutableDictionary *newDic = [NSMutableDictionary dictionaryWithCapacity:0];
        [newDic addEntriesFromDictionary:dic];
        if ([dic.allKeys containsObject:model.ID])
        {
            NSString *numStr = [dic objectForKey:model.ID];
            NSInteger num = [numStr integerValue];
            if (num > 0)
            {
                num--;
            }
            [newDic setObject:[NSString stringWithFormat:@"%ld",num] forKey:model.ID];
        }
        else
        {
            [newDic setObject:@"0" forKey:model.ID];
        }
        [_closeGoodsDic setObject:newDic forKey:model.productSizeId];
    }
    else
    {
        return;
    }
    [_ggTableview reloadData];
    [self changeNum];
    
}

//添加数量
- (void)addBtnAction:(UIButton *)btn
{
    NSInteger index = btn.tag-2200;
    SizeDetailModel *model = _typeGgAry[index];
    if ([_closeGoodsDic.allKeys containsObject:model.productSizeId])
    {
        NSDictionary *dic = [_closeGoodsDic objectForKey:model.productSizeId];
        NSMutableDictionary *newDic = [NSMutableDictionary dictionaryWithCapacity:0];
        [newDic addEntriesFromDictionary:dic];
        if ([dic.allKeys containsObject:model.ID])
        {
            NSString *numStr = [dic objectForKey:model.ID];
            NSInteger num = [numStr integerValue]+1;
            [newDic setObject:[NSString stringWithFormat:@"%ld",num] forKey:model.ID];
        }
        else
        {
            [newDic setObject:@"1" forKey:model.ID];
        }
        [_closeGoodsDic setObject:newDic forKey:model.productSizeId];
    }
    else
    {
        NSMutableDictionary *newDic = [NSMutableDictionary dictionaryWithCapacity:0];
        [newDic setObject:@"1" forKey:model.ID];
        [_closeGoodsDic setObject:newDic forKey:model.productSizeId];

    }
    [_ggTableview reloadData];
    [self changeNum];
}

- (void)changeNum
{
    UIButton *btn = (UIButton *)[titScrollview viewWithTag:_indexrow+500];
    JSBadgeView *jsview = (JSBadgeView *)[btn viewWithTag:_indexrow+1000];
    SizeListModel *sizeModel = _model.productSizeList[_indexrow];
    if ([_closeGoodsDic.allKeys containsObject:sizeModel.ID])
    {
        NSDictionary *dic = [_closeGoodsDic objectForKey:sizeModel.ID];
        NSInteger zongNum = 0;
        for (NSString *key in dic)
        {
            NSString *numStr = [dic objectForKey:key];
            NSInteger num = [numStr integerValue];
            zongNum += num;
        }
        if (zongNum == 0)
        {
            jsview.badgeText = @"";

        }
        else
        {
            jsview.badgeText = [NSString stringWithFormat:@"%ld",zongNum];
        }

    }
    else
    {
        jsview.badgeText = @"";
    }
    [self tongjiNumberAndMoney];
    
}

- (void)tongjiNumberAndMoney
{
    NSInteger zongNum = 0;
    CGFloat zongPrice = 0;
    CGFloat zongIntegral = 0;
    for (NSString *key in _closeGoodsDic)
    {
        NSDictionary *typeDic = [_closeGoodsDic objectForKey:key];
        NSDictionary *typePriceDic = [_priceDic objectForKey:key];
        NSDictionary *integralDic = [_integDic objectForKey:key];
        for (NSString *key22 in typeDic)
        {
            NSString *numStr = [typeDic objectForKey:key22];
            NSString *djprice = [typePriceDic objectForKey:key22];
            NSString *integStr = [integralDic objectForKey:key22];
            NSInteger num = [numStr integerValue];
            CGFloat thePrice = [djprice floatValue];
            CGFloat money = thePrice*num;
            CGFloat integ = [integStr floatValue]*num;
            zongNum += num;
            zongPrice += money;
            zongIntegral += integ;
        }
    }
    _allNumber = zongNum;
    _allPrice = zongPrice;
    _allInteger = zongIntegral;
    
    tongjiLab.text = [NSString stringWithFormat:@"共 %ld 件商品  合计: ￥%.2lf元 + %.0lf积分",zongNum,zongPrice,zongIntegral];
    NSString *zonNumStr = [NSString stringWithFormat:@"%ld",zongNum];
    NSMutableAttributedString *noteString = [[NSMutableAttributedString alloc] initWithString:tongjiLab.text];
    NSRange titleRange = [[noteString string]rangeOfString:[NSString stringWithFormat:@" %.0lf",zongIntegral]];
    NSRange stringRange = NSMakeRange(2, zonNumStr.length);
    NSRange stringRange22 = [[noteString string]rangeOfString:[NSString stringWithFormat:@" ￥%.2lf",zongPrice]];
    [noteString addAttribute:NSForegroundColorAttributeName value:RGB(241, 90, 36) range:titleRange];
    [noteString addAttribute:NSForegroundColorAttributeName value:RGB(241, 90, 36) range:stringRange];
    [noteString addAttribute:NSForegroundColorAttributeName value:RGB(241, 90, 36) range:stringRange22];
    [tongjiLab setAttributedText:noteString];
    
    
}

- (void)requestProductSelect
{
    WEAKSELF;
    NSDictionary *dic = @{@"id":[NSString stringWithFormat:@"%@",_idStr]};
    [HYBaseHandler requestProductSelectParmers:dic Success:^(id obj)
    {
        if ([obj server_Getcodecheck])
        {
            _model = [GoodsModel mj_objectWithKeyValues:obj[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableview reloadData];
                if (_model.productImgList.count > 0)
                {
                    NSMutableArray *imgArray = [NSMutableArray arrayWithCapacity:0];
                    for (ImagelistModel *imgModel in _model.productImgList)
                    {
                        [imgArray addObject:imgModel.imgUrl];
                    }
                    _cycleScrollView.imageURLStringsGroup = imgArray;
                }
                [weakSelf creatCloseGgView];

            });
            [weakSelf getAllGgPrice];

        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}

- (void)getAllGgPrice
{
    NSArray *typeAry = _model.productSizeList;
    for (SizeListModel *model in typeAry)
    {
        NSArray *ggAry = model.productSizeDetailList;
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
        NSMutableDictionary *dic22 = [NSMutableDictionary dictionaryWithCapacity:0];
        for (SizeDetailModel *detaModel in ggAry)
        {
            [dic setObject:detaModel.price forKey:detaModel.ID];
            [dic22 setObject:detaModel.integral forKey:detaModel.ID];
        }
        [_priceDic setObject:dic forKey:model.ID];
        [_integDic setObject:dic forKey:model.ID];

    }
}

- (void)creatCloseGgView
{
    if (!self.closeGgView)
    {
        self.closeGgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _closeGgView.backgroundColor = RGBA(0, 0, 0, 0.5);
        [sharedDelegate.window addSubview:_closeGgView];
        
        UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-480*displaywidth-heightX, SCREEN_HEIGHT, 480*displaywidth)];
        whiteView.backgroundColor = [UIColor whiteColor];
        [_closeGgView addSubview:whiteView];
        UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
        tap1.cancelsTouchesInView = NO;
        [whiteView addGestureRecognizer:tap1];
        UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(25*displaywidth, 15*displaywidth, 70*displaywidth, 70*displaywidth) ImageName:@""];
        if (_model.productImgList.count > 0)
        {
            ImagelistModel *imgModel = _model.productImgList[0];
            [imgView sd_setImageWithURL:[NSURL URLWithString:imgModel.imgUrl]];
        }
        [whiteView addSubview:imgView];
        UILabel *titlab = [ZCControl createLabelWithFrame:CGRectMake(110*displaywidth, 10*displaywidth, SCREEN_WIDTH-145*displaywidth, 30*displaywidth) Font:14.0 Text:[NSString stringWithFormat:@"%@（%@）",_model.productName,_model.unit] Color:RGB(77, 77, 77)];
        titlab.lineBreakMode = NSLineBreakByTruncatingTail;
        [whiteView addSubview:titlab];
        UIButton *backGGBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-30*displaywidth, 10*displaywidth, 20*displaywidth, 20*displaywidth) ImageName:@"guanbi" Target:self Action:@selector(backGGAction) Title:nil Font:12.0];
        backGGBtn.backgroundColor = [UIColor clearColor];
        [whiteView addSubview:backGGBtn];
        UILabel *pricelab = [ZCControl createLabelWithFrame:CGRectMake(110*displaywidth, 45*displaywidth, SCREEN_WIDTH-145*displaywidth, 20*displaywidth) Font:14.0 Text:[_model.priceDescribe stringByAppendingString:@" +"] Color:RGB(241, 90, 36)];
        [whiteView addSubview:pricelab];
        UILabel *integralLab = [ZCControl createLabelWithFrame:CGRectMake(110*displaywidth, 65*displaywidth, 120*displaywidth, 15*displaywidth) Font:11.0 Text:[NSString stringWithFormat:@"%@积分",_model.integral] Color:[UIColor whiteColor]];
        integralLab.textAlignment = NSTextAlignmentCenter;
        integralLab.layer.cornerRadius = 2;
        integralLab.layer.masksToBounds = YES;
        integralLab.backgroundColor = RGB(24, 159, 186);
        [whiteView addSubview:integralLab];
        CGRect bounds1 = [integralLab.text boundingRectWithSize:CGSizeMake(120*displaywidth, 15*displaywidth) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:NormalFontWithSize(11.0+fontScale)} context:nil];
        CGFloat width1 = bounds1.size.width+10;
        if (bounds1.size.width > 120*displaywidth)
        {
            width1 = 120*displaywidth;
        }
        integralLab.frame = CGRectMake(110*displaywidth, 65*displaywidth, width1, 15*displaywidth);
        UIView *lineview = [[UIView alloc] initWithFrame:CGRectMake(0, 90*displaywidth, SCREEN_WIDTH, 1*displaywidth)];
        lineview.backgroundColor = LinesColor;
        [whiteView addSubview:lineview];
        UIImageView *lastImgView = [ZCControl createImageViewWithFrame:CGRectMake(0, 96*displaywidth, 25*displaywidth, 30*displaywidth) ImageName:@"zuohua"];
        lastImgView.contentMode = UIViewContentModeScaleAspectFit;
        [whiteView addSubview:lastImgView];
        UIButton *lastBtn = [ZCControl createButtonWithFrame:CGRectMake(0, 91*displaywidth, 25*displaywidth, 40*displaywidth) ImageName:nil Target:self Action:@selector(lastAction) Title:nil Font:12.0];
        lastBtn.backgroundColor = [UIColor clearColor];
        [whiteView addSubview:lastBtn];

        UIImageView *nextImgView = [ZCControl createImageViewWithFrame:CGRectMake(SCREEN_WIDTH-25*displaywidth, 96*displaywidth, 25*displaywidth, 30*displaywidth) ImageName:@"youhua"];
        nextImgView.contentMode = UIViewContentModeScaleAspectFit;
        [whiteView addSubview:nextImgView];
        UIButton *nextBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-25*displaywidth, 91*displaywidth, 25*displaywidth, 25*displaywidth) ImageName:nil Target:self Action:@selector(nextAction) Title:nil Font:12.0];
        nextBtn.backgroundColor = [UIColor clearColor];
        [whiteView addSubview:nextBtn];
        titScrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(26*displaywidth, 91*displaywidth, SCREEN_WIDTH-52*displaywidth, 40*displaywidth)];
        titScrollview.backgroundColor = [UIColor whiteColor];
        titScrollview.delegate = self;
        titScrollview.contentOffset = CGPointMake(0, 0);
        titScrollview.pagingEnabled = NO;
        titScrollview.bounces = NO;
        titScrollview.showsHorizontalScrollIndicator = YES;
        [whiteView addSubview:titScrollview];
        if (_model.productSizeList.count > 0)
        {
            CGFloat W = (SCREEN_WIDTH-52*displaywidth)/3;
            titScrollview.contentSize = CGSizeMake(W*_model.productSizeList.count, 40*displaywidth);

            for (int i = 0; i < _model.productSizeList.count; i++)
            {
                SizeListModel *sizeModel = _model.productSizeList[i];
                NSString *typename = sizeModel.productSizeName;
                if (typename.length > 5)
                {
                    typename = [NSString stringWithFormat:@"%@...",[typename substringToIndex:5]];
                }
                UIButton *typeBtn = [ZCControl createButtonWithFrame:CGRectMake(W*i, 0, W, 39*displaywidth) ImageName:nil Target:self Action:@selector(closeTypeAction:) Title:typename Font:14.0];
                typeBtn.backgroundColor = [UIColor clearColor];
                [typeBtn setTitleColor:RGB(77, 77, 77) forState:UIControlStateNormal];
                if (i == 0)
                {
                    [typeBtn setTitleColor:ThemeColor forState:UIControlStateNormal];

                }
                if (_model.productSizeList.count == 1)
                {
                    typeBtn.frame = CGRectMake(W, 0, W, 39*displaywidth);
                }
                else if (_model.productSizeList.count == 2)
                {
                    typeBtn.frame = CGRectMake((SCREEN_WIDTH-52*displaywidth)/4-W/2+(SCREEN_WIDTH-52*displaywidth)/2*i, 0, W, 39*displaywidth);
                }
                typeBtn.tag = 500+i;
                [titScrollview addSubview:typeBtn];
                JSBadgeView *badgeView = [[JSBadgeView alloc] initWithParentView:typeBtn alignment:JSBadgeViewAlignmentTopRight];
                badgeView.badgeText = @"";
                badgeView.tag = 1000+i;
                [typeBtn addSubview:badgeView];
            }
            UIButton *btn = (UIButton *)[titScrollview viewWithTag:500];
            bottonLine = [[UIView alloc] initWithFrame:CGRectMake(btn.frame.origin.x+btn.frame.size.width/2-30*displaywidth, 39*displaywidth, 60*displaywidth, 1*displaywidth)];
            bottonLine.backgroundColor = ThemeColor;
            [titScrollview addSubview:bottonLine];
        }
        UIView *line33 = [[UIView alloc] initWithFrame:CGRectMake(0, 131*displaywidth, SCREEN_WIDTH, 4*displaywidth)];
        line33.backgroundColor = LinesColor;
        [whiteView addSubview:line33];
        if (_model.productSizeList.count > 0)
        {
            SizeListModel *sizeModel22 = _model.productSizeList[0];
            _typeGgAry = sizeModel22.productSizeDetailList;
        }
        self.ggTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 135*displaywidth, SCREEN_WIDTH, 300*displaywidth) style:UITableViewStylePlain];
        _ggTableview.delegate = self;
        _ggTableview.dataSource = self;
        _ggTableview.tag = 22;
        _ggTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _ggTableview.backgroundColor = BacksColor;
        [whiteView addSubview:_ggTableview];
        tongjiLab = [ZCControl createLabelWithFrame:CGRectMake(10*displaywidth, 440*displaywidth, SCREEN_WIDTH-120*displaywidth, 35*displaywidth) Font:14.0 Text:@"共 0 件商品  合计：￥0.00元 + 0积分" Color:RGB(77, 77, 77)];
        tongjiLab.textAlignment = NSTextAlignmentRight;
        NSMutableAttributedString *noteString = [[NSMutableAttributedString alloc] initWithString:tongjiLab.text];
        NSRange stringRange = NSMakeRange(2, 1);
        NSRange stringRange22 = [[noteString string]rangeOfString:@"￥0.00"];
        NSRange stringRange33 = NSMakeRange(tongjiLab.text.length-3, 1);
        [noteString addAttribute:NSForegroundColorAttributeName value:RGB(241, 90, 36) range:stringRange];
        [noteString addAttribute:NSForegroundColorAttributeName value:RGB(241, 90, 36) range:stringRange22];
        [noteString addAttribute:NSForegroundColorAttributeName value:RGB(241, 90, 36) range:stringRange33];
        [tongjiLab setAttributedText:noteString];
        [whiteView addSubview:tongjiLab];
        UIButton *soureBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-100*displaywidth, 435*displaywidth, 100*displaywidth, 45*displaywidth) ImageName:nil Target:self Action:@selector(soureAction) Title:@"确定" Font:16.0];
        soureBtn.backgroundColor = ThemeColor;
        [soureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [whiteView addSubview:soureBtn];
    }
    _closeGgView.hidden = YES;
}

//左移
- (void)lastAction
{
    CGFloat X = titScrollview.contentOffset.x+10;
    NSInteger index = X/((SCREEN_WIDTH-52*displaywidth)/3);
    if (index > 0)
    {
        CGFloat newX = (SCREEN_WIDTH-52*displaywidth)/3*(index-1);
        titScrollview.contentOffset = CGPointMake(newX, 0);
    }
    if (_indexrow != 0)
    {
        UIButton *btn = (UIButton *)[titScrollview viewWithTag:_indexrow+499];
        [self closeTypeAction:btn];
    }
}

//右移
- (void)nextAction
{
    CGFloat X = titScrollview.contentOffset.x+10;
    NSInteger index = X/((SCREEN_WIDTH-52*displaywidth)/3);
    if (_model.productSizeList.count > 3)
    {
        if (index < _model.productSizeList.count-3)
        {
            CGFloat newX = (SCREEN_WIDTH-52*displaywidth)/3*(index+1);
            titScrollview.contentOffset = CGPointMake(newX, 0);
        }
    }
    
    if (_indexrow != _model.productSizeList.count-1)
    {
        UIButton *btn = (UIButton *)[titScrollview viewWithTag:_indexrow+501];
        [self closeTypeAction:btn];
    }

}

//确定规格
- (void)soureAction
{
    if (_allNumber == 0)
    {
        [LTools showMBProgressWithText:@"请选择规格" addToView:self.view];
        return;
    }
    [self backGGAction];
    if (_isShopCar)
    {
        
            [self requestAddShoppingCart];
       
    }
    else
    {
        BuyNowViewController *vc = [[BuyNowViewController alloc] init];
        vc.goodModel = _model;
        vc.goodsDic = _closeGoodsDic;
        vc.zongNum = _allNumber;
        vc.zongPrice = _allPrice;
        vc.zongInteger = _allInteger;
        [self.navigationController pushViewController:vc animated:YES];
        
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
//    CGFloat X = scrollView.contentOffset.x;
//    NSInteger index = X/((SCREEN_WIDTH-52*displaywidth)/3);
//    CGFloat newX = (SCREEN_WIDTH-52*displaywidth)/3*index;
//    scrollView.contentOffset = CGPointMake(newX, 0);
    
}

- (void)closeTypeAction:(UIButton *)btn
{
    NSInteger index = btn.tag-500;
    _indexrow = index;
    for (id v in titScrollview.subviews)
    {
        if ([v isKindOfClass:[UIButton class]])
        {
            UIButton *button = (UIButton *)v;
            [button setTitleColor:RGB(77, 77, 77) forState:UIControlStateNormal];

        }
    }
    [btn setTitleColor:ThemeColor forState:UIControlStateNormal];
    bottonLine.frame = CGRectMake(btn.frame.origin.x+btn.frame.size.width/2-30*displaywidth, 39*displaywidth, 60*displaywidth, 1*displaywidth);
    SizeListModel *sizeModel = _model.productSizeList[index];
    _typeGgAry = sizeModel.productSizeDetailList;
    [_ggTableview reloadData];

}

- (void)backGGAction
{
    _closeGgView.hidden = YES;
}

-(void)viewTapped:(UITapGestureRecognizer*)tap1
{
    [_closeGgView endEditing:YES];
    [self.view endEditing:YES];
}
- (void)jianpanhuishou:(NSNotification *)notification
{
    _closeGgView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    _closeGgView.frame = CGRectMake(0, -220*displaywidth, SCREEN_WIDTH, SCREEN_HEIGHT);

}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSInteger index = textField.tag-3000;
    SizeDetailModel *model = _typeGgAry[index];
    if ([_closeGoodsDic.allKeys containsObject:model.productSizeId])
    {
        NSDictionary *dic = [_closeGoodsDic objectForKey:model.productSizeId];
        NSMutableDictionary *newDic = [NSMutableDictionary dictionaryWithCapacity:0];
        [newDic addEntriesFromDictionary:dic];
        [newDic setObject:textField.text forKey:model.ID];
        [_closeGoodsDic setObject:newDic forKey:model.productSizeId];
    }
    else
    {
        NSMutableDictionary *newDic = [NSMutableDictionary dictionaryWithCapacity:0];
        [newDic setObject:textField.text forKey:model.ID];
        [_closeGoodsDic setObject:newDic forKey:model.productSizeId];
        
    }
    [self changeNum];
}

-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    [_closeGgView endEditing:YES];
    [self.view endEditing:YES];
    return indexPath;
}
// 滑动的时候 searchBar 回收键盘

- (void)scrollViewWillBeginDragging:(UIScrollView*)scrollView
{
    [_closeGgView endEditing:YES];
    [self.view endEditing:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_closeGgView endEditing:YES];
    [self.view endEditing:YES];
}


- (void)requestAddShoppingCart
{
    WEAKSELF;
    NSMutableArray *theGgAry = [NSMutableArray arrayWithCapacity:0];
    for (NSString *key in _closeGoodsDic)
    {
        NSDictionary *typeDic = [_closeGoodsDic objectForKey:key];
        for (NSString *key22 in typeDic)
        {
            NSString *numStr = [typeDic objectForKey:key22];
            if ([numStr integerValue] > 0)
            {
                NSDictionary *ggdic = @{@"productSizeDetailId":key22,
                                        @"num":numStr
                                        };
                [theGgAry addObject:ggdic];
            }
        }
    }
    if (theGgAry.count == 0)
    {
        [LTools showMBProgressWithText:@"请选择规格" addToView:self.view];
        return;
    }
    NSDictionary *dic = @{@"productId":_model.ID,
                          @"shoppingCartDetailList":theGgAry
                          };
    [HYBaseHandler requestAddShoppingCartParmers:dic Success:^(id obj)
    {
        if ([obj server_Getcodecheck])
        {
            [LTools showMBProgressWithText:@"添加成功，在购物车等亲哦~" addToView:weakSelf.view];
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
